import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function (location) {
  return originalPush.call(this, location).catch(err => { })
};
Vue.use(VueRouter)

const routes = [
  {
    path: "/",
    redirect: "/home"
  },
  {
    path: '/home',
    name: 'Home',
    component: Home,
    children: [
      {
        path: '/home/searchPopup',
        name: 'SearchPopup',
        //   // route level code-splitting
        //   // this generates a separate chunk (about.[hash].js) for this route
        //   // which is lazy-loaded when the route is visited.
        component: () => import(/* webpackChunkName: "searchPopup" */ '../views/SearchPopup.vue')
      }
    ],
    meta: {
      activeNum: 0,
      isShowTabbar: true
    }
  },
  {
    path: "/special",
    name: "Special",
    component: () => import(/* webpackChunkName: "Special" */ '../views/Special.vue'),
    meta: {
      activeNum: 1,
      isShowTabbar: true
    }

  },
  {
    path: "/classification",
    name: "Classification",
    component: () => import(/* webpackChunkName: "Classification" */ '../views/Classification.vue'),
    meta: {
      activeNum: 2,
      isShowTabbar: true
    }

  },
  {
    path: "/shopcat",
    name: "Shopcat",
    component: () => import(/* webpackChunkName: "Shopcat" */ '../views/Shopcat.vue'),
    meta: {
      activeNum: 3,
      isShowTabbar: true
    }

  },
  {
    path: "/user",
    name: "User",
    component: () => import(/* webpackChunkName: "User" */ '../views/User.vue'),
    meta: {
      isShowTabbar: true,
      activeNum: 4
    }

  },

  {
    path: "/productDetail",
    name: "ProductDetail",
    component: () => import(/* webpackChunkName: "ProductDetail" */ '../views/ProductDetail.vue'),

    meta: {
      isShowTabbar: false
    }
  },
  // {
  //   path: '/about',
  //   name: 'About',
  //   // route level code-splitting
  //   // this generates a separate chunk (about.[hash].js) for this route
  //   // which is lazy-loaded when the route is visited.
  //   component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  // }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})
//路由拦截/路由守卫在发送路由之前拦截下来，判断是否有token
router.beforeEach((to, from, next) => {

  //简单理解，每一次跳转之前都会执行这个函数


  //to 要去往的路由对象 to.path == "/shopcat" 加入成立就表示即将要跳转到购物车
  //from 从哪里出发的路由对象
  //next() 必须要调用next()才能跳转这个页面


  //需求去往购物车页面之前，先判断能不能获取到token值，获取不到就跳转"我的"页面 获取到这届next
  let token = localStorage.getItem("token");
  if (to.path == "/shopcat") {
    if (token) {
      next()
    } else {
      //提示没有登录
      Vue.prototype.$toast("请先登录")
      //跳转
      setTimeout(() => {
        next("/user")
      }, 1000)

    }
    return
  }
  next()//必须调用next()  才能达到要跳转的页面
})

export default router
